from sklearn.metrics import roc_curve, auc
import numpy as np
import matplotlib.pyplot as plt
##y_test相当于真实值，注意，roc曲线仅适用于二分类问题，多分类问题应先转化为二分类
y_test = np.array([1,1,0,1,1,1,0,0,1,0,1,0,1,0,0,0,1,0,1,0])
y_test1 = np.array([1,0,0,1,1,1,1,1,0,1,0,0,1,0,1,1,1,1,0,0])

#y_score 根据x_test预测出的y_pre,根据出现的概率大小进行排列y_test
y_score = np.array([0.9,0.8,0.7,0.6,0.55,0.54,0.53,0.52,0.51,0.505,0.4,0.39,0.38,0.37,0.36,0.35,0.34,0.33,0.3,0.1])
##
fpr,tpr,thre = roc_curve(y_test,y_score)
fpr1,tpr1,thre1 = roc_curve(y_test1,y_score)
##计算auc的值，就是roc曲线下的面积
auc1 = auc(fpr, tpr)
auc2 = auc(fpr1, tpr1)
# print("auc:",auc1,auc2)
# 画图
plt.figure(figsize = (7,6))
plt.plot(fpr,tpr,color = 'darkred',label = 'roc area:(%0.2f)'%auc1)
plt.plot([0,1],[0,1],linestyle = '--')
# plt.plot(fpr1,tpr1,color = 'green',label = 'roc area:(%0.2f)'%auc2)
# plt.plot([0,1],[0,1],linestyle = '--')
plt.xlim([0,1])
plt.ylim([0,1])
plt.rcParams['font.sans-serif']=['SimHei']
plt.rcParams['axes.unicode_minus'] = False
plt.xlabel('假正例率')
plt.ylabel('真正例率')
plt.title('ROC 曲线')
plt.legend(loc = 'lower right')
plt.show()